<template>
  <span >
    <!-- <el-button type="primary" @click="getuploadFileIds" :loading="btnLoad">上传</el-button> -->
    <!-- icon="el-icon-upload"  如需要icon添加上el-button去就好了 -->
    <el-upload
      ref="upload"
      :action="action"
      :data="fileUploadInfoDto"
      :auto-upload="true"
      :limit="limit"
      :before-upload="beforeUpload"
      :on-error="exportError"
      :on-exceed="handleExceed"
      :on-success="uploadSuccess"
      :file-list="fileList"
      :accept="fileType"
      :disabled="disabled"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-preview="ispreview"
      multiple
      name="dmsFile"

    >

      <el-button :disabled="disabled" type="primary" >{{ name }} <i class="el-icon-upload el-icon--right"/></el-button>
    </el-upload>
    <div
      v-if="uploadDiv"
      style="position: fixed;
    left: 52%;
    top: 30%;
    width: 100px;
    height: 100px;
    line-height: 100px;
    border-radius: 14px;
    background: rgb(0, 0, 0);
    color: rgb(255, 255, 255);
    opacity: 0.5;
    text-align: center;">
      正在上传....
    </div>
    <el-dialog :title="title" :visible.sync="isshow" top="5vh" width="500px" append-to-body>
      <!-- <img :src="imgsrc" alt="图片"> -->
      <!-- <img :src="imgsrc" width="100%" @click="downloadImg" > -->
      <el-tooltip class="item" content="双击可放大缩小和旋转" placement="bottom">
        <el-image
          :src="imgsrc"
          :preview-src-list="dialogImageUrlList"
          style="width:100%; height: 100%"/>
      </el-tooltip>
    </el-dialog>
  </span>
</template>
<script>
import SERVER from '@/api/server'
import request from '@/utils/request'
import { deleteById } from '@/api/basedata/file.js'
export default {
  name: 'PublicuploadFj',
  props: {
    url: String,
    billType: [String],
    billId: {
      type: String,
      default: ''
    },
    title: String,
    model: String,
    name: String,
    limit: [Number],
    fileType: String,
    fileDesc: {
      type: String,
      default: ''
    },
    maxSize: [String],
    disabled: {
      type: Boolean,
      default: false
    },
    colors: String
  },
  data() {
    return {
      dialogImageUrlList: [],
      aHref: '',
      uploadDiv: false,
      isshow: false,
      imgsrc: '',
      exportVisible: false,
      btnLoad: false,
      urlparams: {},
      fileUploadInfoDto: {
        billType: this.$props.billType,
        billId: this.$props.billId
      },
      exportData: {
        fileName: '',
        fileSize: '',
        fileUploadId: '',
        errorData: []
      },
      fileslength: 0,
      fileIdStr: '',
      fileUploadIdStr: '',
      fileList: []
    }
  },
  computed: {
    action() {
      return `${SERVER.DMSCLOUD_BASEDATA}/file/save/3`
    }

  },
  watch: {
    billId(val) {
      this.queryFiles()
    }
  },
  mounted() {
    this.queryFiles()
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(`最多上传 ${this.limit} 个文件!`)
    },
    // 导入
    export_in() {
      this.exportVisible = true
    },
    //
    getuploadFileIds() {
      const uploads = this.$refs['upload'].uploadFiles
      for (let i = 0; i < uploads.length; i++) {
        if (uploads[i].key) {
          // 已上传文件id拼接字符串
          this.fileIdStr += ',;' + uploads[i].key
        } else {
          // 新上传文件数量
          this.fileslength += 1
        }
      }
      // 已上传，新上传文件id
      const params = this.fileIdStr.slice(2) + '##@' + this.fileUploadIdStr.slice(2)
      // 添加属性
      this.$set(this.urlparams, this.billType, params)
      this.$emit('getparams', this.urlparams)
    },
    uploadSuccess(res, file, fileList) {
      this.uploadDiv = false
      this.fileUploadIdStr = this.fileUploadIdStr.replace(',;,;', ',;')
      this.fileUploadIdStr += ',;' + res.fileUploadId
      this.count += 1
      this.getuploadFileIds()
    },
    // 点击已选中的文件
    ispreview(file) {
      var img_id = file.name // 根据id得到值
      var index = img_id.indexOf('.') // （考虑严谨用lastIndexOf(".")得到）得到"."在第几位
      img_id = img_id.substring(index) // 截断"."之前的，得到后缀
      if (img_id !== '.bmp' && img_id !== '.png' && img_id !== '.gif' && img_id !== '.jpg' && img_id !== '.jpeg') { // 根据后缀，判断是否符合图片格式
        // var url = window.URL.createObjectURL(file.url)
        window.open(file.url, '_blank')
        // window.location.href=file.url
      } else {
        this.isshow = !this.isshow
        this.imgsrc = file.url
        this.dialogImageUrlList[0] = file.url
      }
    },
    beforeRemove(file, fileList) {
      var id = file.key
      if (id == null || id === '') {
        id = file.response.fileUploadId
      }

      return new Promise((resolve, reject) => {
        this.$confirm('确定要删除\'' + file.name + '\'吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.deleteById(id)
          resolve(true)
        }).catch(() => {
          reject(new Error('获取数据失败'))
        })
      })
    },
    async deleteById(id) {
      deleteById(id).then(response => {
        this.$message({
          type: 'success',
          message: '删除成功！'
        })
      })
    },
    handleRemove(file, fileList) {
      if (file.key === undefined || file.key == null || file.key === '') {
        this.fileUploadIdStr = this.fileUploadIdStr.replace(file.response.fileUploadId, '')
      } else {
        this.fileUploadIdStr = this.fileUploadIdStr.replace(file.key, '')
      }
      if (this.fileUploadIdStr === ',;,;') {
        this.fileUploadIdStr = ',;'
      } else if (this.fileUploadIdStr.indexOf(',;,;') > -1) {
        this.fileUploadIdStr = this.fileUploadIdStr.replace(',;', ',;')
      }
      this.getuploadFileIds()
    },
    beforeUpload(file) {
      if (this.fileType != null && this.fileType !== '' && this.fileType !== undefined && this.fileDesc != null && this.fileDesc !== '' && this.fileDesc !== undefined && this.fileType.indexOf(file.name.substring(file.name.lastIndexOf('.'), file.name.length)) < 0) {
        this.$message({
          type: 'error',
          message: this.fileDesc
        })
        return false
      }
      if (this.maxSize != null && this.maxSize !== '' && this.maxSize !== undefined && file.size / 1024 / 1024 > parseInt(this.maxSize)) {
        this.$message({
          type: 'error',
          message: '上传文件大小需小于' + this.maxSize + 'MB!'
        })
        return false
      }
    },

    queryFiles() {
      this.fileList = []
      // 编辑 查询文件列表
      if (this.billId !== undefined && this.billId !== '') {
        const queryurl = `${SERVER.DMSCLOUD_BASEDATA}/file/billFiles/${
          this.billType
        }/${this.billId}`
        const params = {
          fileType: Number(this.billType),
          billId: this.billId
        }
        request
          .get(queryurl, params)
          .then(response => {
            const fileList = response.initialPreviewConfig
            const urls = response.initialPreview
            console.log(fileList)
            if (fileList !== undefined && fileList.length > 0) {
              this.fileList = []
              for (let i = 0; i < fileList.length; i++) {
                const obj = {}
                obj.name = fileList[i].caption
                obj.key = fileList[i].key
                obj.billType = urls[i].split('/')[3]
                obj.url = `${SERVER.DMSCLOUD_BASEDATA}` + urls[i]
                this.fileList.push(obj)
              }
            }
            this.getuploadFileIds()
          })
          .catch(({ err }) => {})
      }
    },
    // 已上传附件列表
    async listfileUploadInfoDto() {
    },
    exportError(response, file) {
      this.exportVisible = false
      this.$message({
        type: 'error',
        message: JSON.parse(response.message).errorData[0].errorMsg
      })
      this.fileList = []
    }
  }
}
</script>
<style scoped>
.publicupload{
  display: flex;
}
.publicupload div{
}
</style>

